//
//  CaptureViewController.m
//  AlinkDemo
//
//  Created by Vincent on 2017/11/1.
//  Copyright © 2017年 aliyun. All rights reserved.
//

#import "CaptureEditViewController.h"
#import "PopCalendarViewController.h"
#import "CaptureCollectionViewCell.h"
#import <MWPhotoBrowser.h>
#import "DeleteViewController.h"

@interface CaptureEditViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,MWPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UIButton *typeButton;
@property (weak, nonatomic) IBOutlet UIButton *dateButton;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (nonatomic,strong) UIImageView *noMsgImageView;;


@property(nonatomic,retain)NSMutableArray *selectDatas;//接收数据源结果
@property (nonatomic,strong) NSMutableArray *logs;
@property (nonatomic,strong) NSMutableArray *photos;
@property (nonatomic,strong) NSDateFormatter *dateFormatter;

@property (nonatomic,assign) BOOL isEditing;

@end
static NSString *const cellId = @"cellId";

@implementation CaptureEditViewController

- (UIImageView *)noMsgImageView{
    if (!_noMsgImageView) {
        _noMsgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 120, SCREEN_WIDTH, SCREEN_WIDTH)];
        _noMsgImageView.contentMode = UIViewContentModeScaleAspectFit;
        _noMsgImageView.image = [UIImage imageNamed:@"capture_no_msg"];
    }
    
    return _noMsgImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //    self.collectionView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    [self.collectionView  registerNib:[UINib nibWithNibName:@"CaptureCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellId];
    self.collectionView.allowsMultipleSelection=YES;
    self.collectionView.allowsSelection=YES;
    self.dateFormatter = [[NSDateFormatter alloc] init];
    [self.typeButton setTitle:@"抓拍记录" forState:UIControlStateNormal];
    self.tabBarController.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self setEditing:YES animated:YES];
    
}

- (void)closeAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)selectAllAction{
    
    if (self.logs.count==0) {
        
        return;
    }
    for (int i = 0; i < self.logs.count; i++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionTop];
    }
    [self.selectDatas removeAllObjects];
    
    [self.selectDatas addObjectsFromArray:self.logs];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消全选" style:UIBarButtonItemStyleDone target:self action:@selector(unselectAllAction)];
    
}

-(void)unselectAllAction{
    if (self.logs.count==0) {
        
        return;
    }
    for (int i = 0; i < self.logs.count; i++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
    }
    [self.selectDatas removeAllObjects];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStyleDone target:self action:@selector(selectAllAction)];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.selectDatas removeAllObjects];
    [self.dateFormatter setDateFormat:@"yy-MM-dd 00:00:00"];
    NSString *dateString = [self.dateFormatter stringFromDate:self.currentDate?self.currentDate:[NSDate date]];
    [self refresh:[self.dateFormatter dateFromString:dateString]];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)refresh:(NSDate *)date{
    
    [self.logs removeAllObjects];
    [self.dateFormatter setDateFormat:@"MM-dd"];
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    [self.dateButton setTitle:dateString forState:UIControlStateNormal];
    self.currentDate = date;
    
    [self.dateFormatter setDateFormat:@"yy-MM-dd"];
    dateString = [self.dateFormatter stringFromDate:date];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSString *path = [ NSSearchPathForDirectoriesInDomains( NSDocumentDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];
    
    path = [[[[path stringByAppendingPathComponent:@"capture"] stringByAppendingPathComponent:self.deviceDict[@"bid"]] stringByAppendingPathComponent:dateString]stringByDeletingPathExtension];
    NSArray *images = [fm contentsOfDirectoryAtPath:path error:nil];
    
    NSMutableArray *imagePaths;
    if (images.count>0) {
        imagePaths = [[NSMutableArray alloc] init];
        NSMutableDictionary *dict;
        for (NSString *image in images) {
            
            NSString *url = [path stringByAppendingPathComponent:image];
            NSLog(@"%@",url);
            [imagePaths addObject:[MWPhoto photoWithURL:[NSURL fileURLWithPath:url]]];
            dict = [[NSMutableDictionary alloc] init];
            [dict setValue:url forKey:@"path"];
            [dict setValue:@0 forKey:@"selected"];
            [self.logs addObject:dict];
            
        }
        [self.noMsgImageView removeFromSuperview];
    }else{
        [self.view addSubview:self.noMsgImageView];
    }
    
    [self.photos removeAllObjects];
    if (imagePaths.count>0) {
        [self.photos addObjectsFromArray:imagePaths];
        
    }
    
    [self.collectionView reloadData];
    
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    
    self.isEditing = !self.isEditing;
    [self.collectionView reloadData];
    
    
    if (!editing) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(closeAction)];
        
    }else{
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStyleDone target:self action:@selector(selectAllAction)];
        
    }
    
    if (self.selectDatas.count>0) {

        [self deleteAlert];
    }
    
}


- (void)deleteAlert{

    DeleteViewController *vc= [[DeleteViewController alloc] initWithNibName:@"DeleteViewController" bundle:nil];

    __weak typeof(self) weakSelf = self;

    vc.conformBlock = ^(BOOL isDelete) {

        if (weakSelf.selectDatas.count>0) {

            NSFileManager *fm = [NSFileManager defaultManager];


            for (int i=0; i<weakSelf.selectDatas.count; i++) {

                NSDictionary *dic = self.selectDatas[i];
                NSString *path = dic[@"path"];

                [fm removeItemAtPath:path error:nil];
                [weakSelf.logs removeObject:dic];
                NSLog(@"%@",self.selectDatas);

                NSLog(@"%@",self.logs);
            }

            [weakSelf.collectionView reloadData];
            [weakSelf.selectDatas removeAllObjects];
        }
    };

    vc.cancelBlock = ^{
        
     
        if (weakSelf.logs.count==0) {

            return;
        }
        for (int i = 0; i < weakSelf.logs.count; i++) {

            NSDictionary *dict = weakSelf.logs[i];
            [dict setValue:@0 forKey:@"selected"];

            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [weakSelf.collectionView deselectItemAtIndexPath:indexPath animated:NO];
        }
        [self.selectDatas removeAllObjects];

    };

    MZFormSheetPresentationViewController *sheet = [[MZFormSheetPresentationViewController alloc] initWithContentViewController:vc];
    sheet.presentationController.contentViewSize = CGSizeMake(280, 200);
    sheet.presentationController.shouldDismissOnBackgroundViewTap = NO;
    sheet.contentViewCornerRadius=5.f;
    sheet.presentationController.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppearsCenterVertically;

    sheet.contentViewControllerTransitionStyle=MZFormSheetPresentationTransitionStyleDropDown;
    sheet.presentationController.shouldCenterVertically= YES;
    sheet.presentationController.shouldCenterHorizontally= YES;
    sheet.willDismissContentViewControllerHandler=^(UIViewController *v){

    };

    [self presentViewController:sheet animated:YES completion:nil];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

#pragma mark - MWPhotoBrowser

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}


-(void)initPhotoBrowserWithImages:(NSInteger )currentIndex{
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = NO; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    browser.autoPlayOnAppear = NO; // Auto-play first video
    
    // Customise selection images to change colours if required
    browser.customImageSelectedIconName = @"ImageSelected.png";
    browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
    
    // Optionally set the current visible photo before displaying
    [browser setCurrentPhotoIndex:currentIndex];
    
    // Present
    [self.navigationController pushViewController:browser animated:YES];
    
    // Manipulate
    [browser showNextPhotoAnimated:YES];
    [browser showPreviousPhotoAnimated:YES];
}



- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.logs.count;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = (SCREEN_WIDTH-30)/3;
    return CGSizeMake(width, width);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CaptureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    NSDictionary *log = self.logs[indexPath.row];
    
    [cell.selectedImageView setHidden:!self.isEditing];
    
    NSNumber *selected = log[@"selected"];
    if (selected.integerValue==1) {
        cell.selectedImageView.highlighted = YES;
    }else{
        cell.selectedImageView.highlighted = NO;
    }
    
    cell.captureImageView.image = [UIImage imageWithContentsOfFile:log[@"path"]];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *log = self.logs[indexPath.row];
    CaptureCollectionViewCell *cell = (CaptureCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    
    if (!self.isEditing) {
        
        [self initPhotoBrowserWithImages:indexPath.row];
    }else{
        
        cell.selectedImageView.highlighted = NO;
        [log setValue:@0 forKey:@"selected"];
        [self.selectDatas removeObject:log];
        
    }
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *log = self.logs[indexPath.row];
    CaptureCollectionViewCell *cell = (CaptureCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    
    if (!self.isEditing) {
        
        [self initPhotoBrowserWithImages:indexPath.row];
    }else{
        
        cell.selectedImageView.highlighted = YES;
        [log setValue:@1 forKey:@"selected"];
        [self.selectDatas addObject:log];
        
    }
    
    
}

- (IBAction)buttonClick:(UIButton *)sender {
    
    if (self.isEditing) {
        return;
    }
    if (sender.tag==1) {
        PopCalendarViewController *vc= [[PopCalendarViewController alloc]  init];
        vc.bid = self.deviceDict[@"bid"];
        vc.currentDate = self.currentDate;
        __weak typeof(self) weakSelf = self;
        vc.selectDateBlock = ^(NSDate *date) {
            
            [weakSelf refresh:date];
        };
        MZFormSheetPresentationViewController *sheet = [[MZFormSheetPresentationViewController alloc] initWithContentViewController:vc];
        sheet.presentationController.contentViewSize = CGSizeMake(SCREEN_WIDTH, 300);
        sheet.presentationController.shouldDismissOnBackgroundViewTap = YES;
        sheet.contentViewCornerRadius=0.f;
        sheet.presentationController.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppearsCenterVertically;
        sheet.contentViewControllerTransitionStyle=MZFormSheetPresentationTransitionStyleSlideFromTop;
        sheet.presentationController.portraitTopInset=46+40;
        sheet.willDismissContentViewControllerHandler=^(UIViewController *v){
            
        };
        
        [self presentViewController:sheet animated:YES completion:nil];
        
    }
}


- (NSMutableArray *)logs{
    
    if (!_logs) {
        _logs = [[NSMutableArray alloc] init];
    }
    
    return _logs;
}

- (NSMutableArray *)selectDatas{
    
    if (!_selectDatas) {
        _selectDatas = [[NSMutableArray alloc] init];
    }
    
    return _selectDatas;
}


- (NSMutableArray *)photos{
    
    if (!_photos) {
        _photos = [[NSMutableArray alloc] init];
    }
    
    return _photos;
}



@end
